/*
* @Author: jh
* @Date: 2018/4/10
* @description: 系统 用户添加
*/
<template>
  <div>
     <el-dialog custom-class="cm-el-dialog" :title="id==='-1'?'添加用户':'编辑用户'" :visible=true center width="45%" :before-close="isShowAddFun" :close-on-click-modal=false :append-to-body=true>
        <el-form :model="sysUserInfo"  ref="form" label-width="85px" :rules="rules">
            <el-form-item label="用户名称" prop='name'>
              <el-input v-model="sysUserInfo.name" auto-complete="off" :maxLength="50" placeholder="请输入用户名称"></el-input>
            </el-form-item>
            <el-form-item label="所属角色" prop='roleName'>
                <el-select v-model="sysUserInfo.roleId" placeholder="请选择活动区域" class="el-select-100" @change='changeRole(sysUserInfo.roleId)'>
                    <!-- <el-option label="请选择" value=""></el-option> -->
                    <el-option v-for="(item,index) in roleList"
                        :key="index"
                        :label="item.roleName" 
                        :value="item.id" >
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="登录账号" prop='accout' >
                <el-input v-model="sysUserInfo.accout" :maxLength="20" placeholder="请输入登录账号" :disabled="id!=='-1'"></el-input>
            </el-form-item>
            <!-- 添加 -->
            <el-form-item label="密码" prop='password' v-if="id==='-1'">
                <el-input v-model="sysUserInfo.password"  type="password"  :maxLength="20" placeholder="请输入密码"></el-input>
            </el-form-item>
             <el-form-item label="确认密码" prop='repeatPaw' v-if="id==='-1'">
                <el-input v-model="sysUserInfo.repeatPaw" type="password" :maxLength="20" placeholder="请再次输入密码"></el-input>
            </el-form-item>
            <!-- 编辑 -->
              <el-form-item label="密码" prop='password'  v-if="id !=='-1'" @click.native="changePassConfirm">
                <el-input v-model="sysUserInfo.password" type="password" class='ca-pwdDisabled' :disabled="!changePwdFlag"  :maxLength="20" placeholder="请输入密码"></el-input>
            </el-form-item>
             <el-form-item label="确认密码" prop='repeatPaw'  v-if="id !=='-1'" @click.native="changePassConfirm">
                <el-input v-model="sysUserInfo.repeatPaw" type="password" class='ca-pwdDisabled' :disabled="!changePwdFlag" :maxLength="20" placeholder="请再次输入密码"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop='phoneNumber'>
                <el-input v-model="sysUserInfo.phoneNumber" :maxLength="11" placeholder="请输入11位手机号码"></el-input>
            </el-form-item>
             <el-form-item label="邮箱" prop='email'>
                <el-input v-model="sysUserInfo.email" :maxLength="20" placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <!-- 1-激活0未激活 , -->
             <el-form-item label="状态" prop='activateStatus'>
                <el-select v-model="sysUserInfo.activateStatus" placeholder="请选择活动区域" class="el-select-100">
                    <!-- <el-option label="请选择" value=""></el-option> -->
                    <el-option v-for="(item,index) in activeStatus" 
                        :key="index"
                        :label="item.dictName" 
                        :value="item.dictValue" >
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="备注" prop='remark'>
                <el-input v-model="sysUserInfo.remark" type="textarea" :maxLength="2000" placeholder="请输入备注"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" >
            <el-button @click="isShowAddFun" round>取 消</el-button>
            <!-- <el-button type="primary" @click="addRole('form')" round>提交</el-button> -->
             <el-button type="primary" @click="validationField('form')" round>提交</el-button>
        </div>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import Vue from 'vue';
import { Component, Watch, Prop } from 'vue-property-decorator';
import UserService from '../../../service/system-config/user';
import { SysUserVO, SysUser } from '../../../api/Interface';
// interface Form {
//     repeatPaw: string;        // 确认密码 ,
//     roleId: string;           // 角色Id ,
//     roleName: string;         // 角色名称 ,
//     // -------------------------------------------
//     accout: string;           // 登陆账号 ,
//     activateStatus: string;   // 激活状态1-激活0未激活 ,
//     createTime: string;       // 创建时间 ,
//     createrId: string;
//     email: string;            // 邮箱 ,
//     id: string;
//     lastLogin: string;        // 最后一次登录时间 ,
//     modiferId: string;
//     modifyTime: string;       // 修改时间 ,
//     name: string;             // 用户名 ,
//     password: string;         // 登录密码 ,
//     phoneNumber: string;      // 手机号 ,
//     remark: string;           // 备注 ,
//     activateStatus: number;
// }
interface SysUserInfo extends SysUser {
    repeatPaw: string;        // 确认密码 ,
    roleId: string;           // 角色Id ,
    roleName: string;         // 角色名称 ,
}
@Component({
  components: { }
})
export default class CompanyList extends Vue {
  // 初始化数据 相当于data
  public msg: number = 123;
  public sysUserInfo: SysUserInfo = {} as SysUserInfo; // activateStatus激活状态1-激活0未激活
  public sysUserInfoParams: SysUserVO = { } as SysUserVO; // 要传的参数
  public activeStatus: object[] = this.$store.state.user.dictionary.dicList.userState; // 用户状态
  public changePwdFlag: boolean = false; // 是否修改密码
  public rules: object = {
      name: [
              { required: true, message: '请输入用户名称', trigger: 'blur' },
      ],
      roleName: [
              { required: true, message: '请选择用户角色', trigger: 'change' },
      ],
      accout: [
              { required: true, message: '请输入登录账号', trigger: 'blur' }, 
      ],
      password: [
               { required: true, validator: this.validatePass, trigger: 'blur' },
      ],
      repeatPaw: [
               {required: true, validator: this.validatePass2, trigger: 'blur' },
      ],
      phoneNumber: [
              {required: false, validator: this.validatePhone, trigger: 'blur' },
      ],
      email: [
               { required: false, message: '请输入邮箱地址', trigger: 'blur' },
               { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      activateStatus: [
              { required: true, message: '请输入客户状态', trigger: 'change' },
      ],
  };
  // refs
  public $refs: {
    form: HTMLFormElement
   };
  @Prop()
  public isShowAddFun: () => void;
  @Prop({default: '-1'})
  public id: string;
  @Prop({default: []})
  public roleList: object[];
  // watch
  @Watch('msg')
  public onChildChanged(val: string, oldVal: string) {
    return val + '***';
  }
  // 方法
  // 声明周期钩子
  public mounted() {
    // console.log(this.activeStatus);
    // this.getUserList();
    if (this.id !== '-1') {
       this.getDetail();
    }
  }
  public created() {
    // this.getUserList();
  }
  // 验证密码
  public validatePass(rule: object, value: string, callback: (obj ?: object) => void) {
    if (!value || value === '') {
      callback(new Error('请输入密码'));
    } else {
      if (this.sysUserInfo.repeatPaw !== '') {
        this.$refs.form.validateField('repeatPaw');
      }
      callback();
    }
  }
  // 验证确认密码
  public validatePass2(rule: object, value: string, callback: (obj ?: object) => void) {
    if (!value || value === '') {
      callback(new Error('请再次输入密码'));
    } else if (value !== this.sysUserInfo.password) {
      callback(new Error('两次输入密码不一致!'));
    } else {
      callback();
    }
  }
  //验证电话
  public validatePhone(rule: object, value: string, callback: (obj ?: object) => void) {
      // if (value === '' || value === null) {
      //     callback(new Error('请输入移动电话'));
      // } else {
      //     if (!(/^1(3|4|5|7|8)\d{9}$/.test(value))) {
      //         callback(new Error('移动电话输入有误'));
      //     } else {
      //         callback();
      //     }
      // }
      if (value && !(/^1(3|4|5|7|8)\d{9}$/.test(value))) {
          callback(new Error('移动电话输入有误'));
      } else {
           callback();
      }
  }
  // 进入修改密码状态
  public changePassConfirm() {
      if (!this.changePwdFlag) {
          this.$confirm('是否重置密码?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
          }).then(() => {
              //清空密码
              this.sysUserInfo.repeatPaw = '';
              this.sysUserInfo.password = '';
              this.changePwdFlag = true;
          }).catch(() => {
              return;
          });
      }
  }
  // 角色改变
  public changeRole(val: string) {
     this.roleList.map(( item: any ) => {
        if (item.id === val) {
          this.sysUserInfo.roleName = item.roleName;
        }
     });
  }
  //验证字段
  public validationField(formName: string) {
      this.$refs[formName].validate((valid) => {
          if (valid) {
            this.saveUser();
          } else {
            return;
          }
      });
  }
  // 重置表单
  public resetForm(formName: string) {
    this.$refs[formName].resetFields();
  }
   //添加用户接口 or 编辑
  public async saveUser() {
      // 数据处理
      // 给传递的参数 赋值
      const temporaryData = Object.assign({}, this.sysUserInfo);
      this.sysUserInfoParams.roleId = temporaryData.roleId;
      this.sysUserInfoParams.roleName = temporaryData.roleName;
      this.sysUserInfoParams.repeatPaw = temporaryData.repeatPaw;

      delete temporaryData.roleId;
      delete temporaryData.roleName;
      delete temporaryData.repeatPaw;

      this.sysUserInfoParams.sysUser = Object.assign({}, temporaryData);

      if (this.id === '-1') { // 添加
        const res = await UserService.sysUserInsert(this.sysUserInfoParams);
        if (res.resCode === '0') {
            this.$emit('getUserList'); //重新获取列表数据
            this.$confirm('已保存至用户列表', '保存成功', {
                confirmButtonText: '继续操作',
                cancelButtonText: '返回列表页',
                type: 'success'
            }).then(() => {
                this.resetForm('form'); // 重置表单 
                this.changePwdFlag = false;
            }).catch(() => {
                this.isShowAddFun(); // 关闭弹框     
            });
        }     
      } else {
            if ( this.sysUserInfo.password === '******' ) {
                this.sysUserInfoParams.sysUser.password = '';
                this.sysUserInfoParams.repeatPaw = '';
            }
            const res = await UserService.sysUserUpdate(this.sysUserInfoParams);
            if (res.resCode === '0') {
                // this.$message({
                //     message: '用户编辑成功!',
                //     type: 'success',
                //     center: true
                // });
                // this.isShowAddFun(); //关闭弹框
                // this.$emit('getUserList'); //重新获取列表数据
                this.$emit('getUserList'); //重新获取列表数据
                this.$confirm('已保存至用户列表', '保存成功', {
                    confirmButtonText: '继续操作',
                    cancelButtonText: '返回列表页',
                    type: 'success'
                }).then(() => {
                    this.getDetail();
                    this.changePwdFlag = false;
                }).catch(() => {
                    this.isShowAddFun(); // 关闭弹框     
                });
          }     
        }    
  }
  //获取用户详情
  public async getDetail() {
      const res = await UserService.getSysUserById(this.id);
      this.sysUserInfoParams = res;

      this.sysUserInfo = JSON.parse(JSON.stringify(this.sysUserInfoParams.sysUser));
     
      this.sysUserInfo.roleId = this.sysUserInfoParams.roleId ; 
      this.sysUserInfo.roleName = this.sysUserInfoParams.roleName;
      // this.sysUserInfo.repeatPaw = this.sysUserInfoParams.repeatPaw; // 密码不显示明文，不用赋值，下面会重置密码
      
      //重置密码
      this.sysUserInfo.repeatPaw = '******';
      this.sysUserInfo.password = '******';
  }
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>